package com.cyx.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import javax.xml.ws.WebEndpoint;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

    /**
     * 配置数据源，让数据源属性和yaml中的配置自动匹配赋值
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource(){
        return new DruidDataSource();
    }

    /**
     * SpringBoot下使用Servlet的样例,druid提供一个监控功能，注入IOC一个监控Servlet就可以访问
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean =
                new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
        HashMap<String,String> params = new HashMap<>();
        params.put("loginUsername","admin");
        params.put("loginPassword","12345");
        bean.setInitParameters(params);
        return bean;
    }

    /**
     * 注册一个过滤器,剔除不统计的请求
     * @return
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //过滤不监控的请求
        Map<String,String> params = new HashMap<>();
        params.put("exclusions","*.js,*.css,/druid/**");
        bean.setInitParameters(params);
        return bean;
    }

}
